package library.net.retrofit.observer;

import android.util.Log;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import library.net.retrofit.exception.RxExceptionHandler;

/**
 * @author Created by qiang.hou on 2018/11/21.
 * @version 1.0
 */
public abstract class RxObserver<T> implements Observer<T> {
    private final static String TAG = "RxObserver";
    private Disposable disposable;

    public RxObserver() {
    }

    @Override
    public void onSubscribe(Disposable d) {
        Log.i(TAG, "sky_dreaming on onSubscribe");
        disposable = d;
    }

    @Override
    public void onError(Throwable e) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

        if (e != null) {
            Log.e(TAG, "sky_dreaming on onError e !instanceof Throwable = "
                    + e.toString());
            doError(RxExceptionHandler.handleException(e));
        } else {
            Log.e(TAG, "sky_dreaming on onError exception is null");
        }
    }

    @Override
    public void onComplete() {
        Log.i(TAG, "sky_dreaming on onComplete");
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    protected abstract void doError(Throwable e);
}
